<?php
    function getFans($uid=0){
        $array = array("code" => 200, "message" => "", "data" => null);
        $uid = intval($uid);//转换成整型ID
    
        if($uid == 0){
            $array["code"] = 400;
            $array["message"] = "UID不能为空!";
        }else{
	        $hander = curl_init();
            $url ="https://api.bilibili.com/x/relation/followers?vmid=".$uid."&pn=1&ps=20&order=desc";
            curl_setopt ($hander,CURLOPT_USERAGENT ,"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36");
	        curl_setopt ($hander, CURLOPT_CUSTOMREQUEST, 'GET');  
	        curl_setopt($hander,CURLOPT_URL,$url);
	        curl_setopt($hander,CURLOPT_HEADER,0);
	        curl_setopt($hander, CURLOPT_RETURNTRANSFER, 1);
	        curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
	        curl_setopt($hander,CURLOPT_TIMEOUT,600);//超时时间10min,超过了估计也down不下来
	        curl_setopt($hander, CURLOPT_SSL_VERIFYPEER, false);
	        curl_setopt($hander, CURLOPT_SSL_VERIFYHOST, false);
            $content=curl_exec($hander);
	        $decode=json_decode($content,true);
	        if($decode['code'] == 0){
                $fans_number=$decode['data']['total'];
                $array["code"] = 200;
                $array["message"] = "Bilibili粉丝数获取成功";
	            $array["data"] = $fans_number;
	        }else{
                $array["code"] = 400;
                $array["message"] = "Bilibili粉丝数获取错误";
	            $array["data"] = $content;
            }
        }
        return $array;  
    }

    function main($event, $context) {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: PUT, GET, POST");
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
        if(isset($event->queryStringParameters->uid)){
            return json_encode(getFans($event->queryStringParameters->uid));
        }else{
            $array = array("code" => 400, "message" => "UID参数缺省!", "data" => null);
	        return json_encode($array);
        }
    }
?>